/* **************************************************************************/
/*COPYRIGHT CCWIN-IN ALL RIGHTS RESERVED. THIS IS AN UNPUBLISHED WORK.      */
/*V8:ConvertMode=API                                                     */
/*V8:WebEnabled=Yes                                                         */
/*V8:RunMode=Character,Windows                                              */
/*EXTRACTING DATA FROM MFG/PRO                                              */
/****************************************************************************/
/* PROCEDURE NAME        : xxsuppliermainapi.p                            */
/* PROCEDURE TYPE        : supplier API Process                             */
/* DESCRIPTION           : Supplier Create API Process                      */
/*                                                                          */     
/* INCLUDE FILES         :                                                  */
/* CALLED BY             :                                                  */
/* CALLED PROCEDURES     :                                                  */
/****************************************************************************/
/* CREATED BY            : Gaoyan                               04-Jul-20   */
/* CREATED BY            : Gaoyan                               21-OCT-24   */
/****************************************************************************/ 
/****************************************************************************/
/****************************************************************************/

{us/mf/mfdtitle.i}
{us/bbi/gplabel.i}
{us/wb/wbrp01.i}
{us/gp/gpuid.i}


{xxjson.i}
{xxcimload.i}

{xxapilog.i}


&SCOPED-DEFINE TimeStamp1 substring(string(year(today), "9999"),3) + string(month(today), "99") + string(day(today), "99")
&SCOPED-DEFINE TimeStamp2 substring(string(time, "HH:MM:SS"), 1, 2) + substring(string(time, "HH:MM:SS"), 4, 2) + substring(string(time, "HH:MM:SS"), 7, 2)

define input parameter vc_inputjson             as character format "x(60)" no-undo.
define input parameter vc_outputjson            as character format "x(60)" no-undo.
define input parameter vc_import                as logical  no-undo.


define variable l_update              as logical                  no-undo.
define variable v_apiresult           as character                no-undo.
define variable v_errflag             as logical   initial yes    no-undo.
define variable v_curtaskid           as character                no-undo.
define variable v_cnt                 as integer                  no-undo.
define variable m_error               as integer                  no-undo.
define variable m_wrng                as integer                  no-undo.

DEFINE VARIABLE li_access           AS    INTEGER                       NO-UNDO.
define variable l_file                       as character format "x(40)" no-undo.
define variable l_line                       as character   no-undo.
define variable lvi_row_id                   as decimal     no-undo.
define variable v_site                       like si_site   no-undo.

define variable l_error                      as character      no-undo.
define stream f_log.
define stream f_cim.
define variable v_quote               as character initial """"   no-undo.
define variable v_default             as character initial "-"    no-undo.
define variable v_space               as character initial " "    no-undo.
define variable v_log                 as character                no-undo.
define variable v_cim                 as character                no-undo.
define variable v_fline               as character                no-undo.
define variable v_errorstatus         as logical                  no-undo.
define variable v_toterrorstatus      as logical initial no      no-undo.
define variable v_errstring           as character                no-undo.
define variable v_status              as character                no-undo.
define variable v_errorcnt            as integer                  no-undo.
define variable vi_reccount            as integer                  no-undo.
define variable v_entity              like si_entity              no-undo.
define variable v_ee                  as logic                    no-undo.

define variable vi_filecount          as integer                  no-undo.
define variable vc_filename           as character                no-undo.
define variable vc_topath             as character                no-undo.
define variable v_runproagram        as character                no-undo.
define variable vc_traceid            as character                no-undo.

define variable hdataset_ret          as handle                   no-undo.


/* ======== for api ========= */
define variable vireturn                     as integer     no-undo.
define variable ilreturndataset              as logical     no-undo.
define variable ilpartialupdate              as logical     no-undo.
define variable icpartialupdateexceptionlist as character   no-undo.
define variable ocprimarykey                 as character   no-undo.
define variable ocrowid                      as character   no-undo.
define variable oidraftinstance              as integer     no-undo.
define variable ocprimarykeyname             as character   no-undo.
define variable vho                          as handle.
define variable oireturnstatus               as integer     no-undo. 
define variable m_company                    like company.companycode no-undo.
define variable m_busnrelid1                 as integer no-undo.
define variable m_addid                      as integer no-undo.
define variable m_length                     as integer no-undo.
  

{ proxy/bbusinessrelationdef.i}
{ proxy/bcreditordef.i} 

define new shared temp-table tt_tbusinessrelation like tbusinessrelation
                  field tt_traceid as character
                  field tt_dataid as character
                  
                  .
define new shared temp-table tt_taddress          like taddress
                  field tt_businessrelationcode as character
                  field tt_traceid as character
                  field tt_dataid as character.
define new shared temp-table tt_tcontact          like tcontact
                  field tt_businessrelationcode as character
                  field tt_addressname as character
                  field tt_traceid as character
                  field tt_dataid as character.
define new shared temp-table tt_tfcmessages       like tfcmessages.
define new shared temp-table tt_tcreditor         like tcreditor 
                  field tt_daybook as character
                  field tt_site    as character
                  field tt_traceid as character
                  field tt_dataid as character.
define new shared temp-table tt_tcreditorvat      like tcreditorvat.
define new shared temp-table tt_tBankNumberRefCreditor like BankNumber
                  field tt_traceid as character
                  field tt_dataid as character.

/* for cimload */
define variable  m_cimfile          as character no-undo.
define variable  m_logfile          as character no-undo.
define variable  m_line             as character no-undo.

define stream f_output.



DEFINE DATASET dsSupplierMaster FOR tt_tcreditor , tt_tbusinessrelation, tt_taddress, tt_tcontact , tt_tBankNumberRefCreditor .
         
 hdataset = dataset dsSupplierMaster:HANDLE.    

/* define variables for program logic */

 output stream f_output to /home/mfg/xxsupplierapi.log.
  put stream f_output "befor mainloop" skip.
  
mainloop:
repeat:

   /* Output and Batch Input */
   
   {us/xx/xxworkpath_e.i &outbound=YES &inbound=no &archive=YES}
   assign
      m_outpath     = m_outpath + "vd/"
      m_archpath    = m_archpath + "vd/"
      m_successpath = m_successpath + "vd/"
      m_errorpath   = m_errorpath + "vd/"
      m_workpath    = m_workpath + "vd/".
   
   
    empty temp-table tt_tbusinessrelation .
    empty temp-table tt_taddress          .
    empty temp-table tt_tcontact          .
    empty temp-table tt_tfcmessages       .
    empty temp-table tt_tcreditor         .
    empty temp-table tt_tcreditorvat      .
   
   v_errorstatus = no.
   vl_RetOK  = no.
   
   /* Load creditor data from JSON  */ 
   vc_outputjson = replace(vc_inputjson,".json",".run.out.json").   
   run loadjsonfile(input vc_inputjson,
                    input vc_outputjson,
                    output vl_RetOK).
                    
   for each tt_tcreditor .
   put stream f_output tt_tcreditor.creditorcode " " tt_tcreditor.tt_traceid skip.
   end.
   for each tt_tbusinessrelation .
   put stream f_output tt_tbusinessrelation.BusinessRelationCode " " tt_tbusinessrelation.tt_traceid skip.
   end.

   
   vc_traceid = "ERROR".
   if vl_RetOK then
   do:
      find first tt_tcreditor no-error.
      assign vc_traceid = tt_tcreditor.tt_traceid.
   end.
   
   if not vl_RetOK then
   assign v_errorstatus = yes.


        

    for each tt_tcreditor :
     put stream f_output "before run xxbusinessrelcrapi" skip.
     v_errorcnt = 0.
    /* message "BR PR" vc_traceid view-as alert-box. */
    {us/bbi/gprun.i ""xxbusinessrelcrapi.p"" "(input vc_traceid,
                                             input  vc_import,
                                             output v_errflag,
                                             output v_apiresult)"}
    put stream f_output unformatted  "br v_errflag:" v_errflag " " v_apiresult skip.
    if v_errflag then 
    do:
    v_errorcnt = v_errorcnt + 1.
    v_errorstatus = yes.
    create api_status.
                  assign api_status.data_seq     = v_errorcnt
                         api_status.return_status  = "FAILED"
                         api_status.message_type = "AFTER-Validtion"
                         api_status.message_string  = v_apiresult
                         api_status.dataid  =  ""
                         api_status.billnbr =  tt_tcreditor.CreditorCode                     
                         api_status.traceid = vc_traceid 
                         api_status.domain = global_domain.
    
    end.
    
 
    /** when businessrelation code already exist or load successfully **/
    if not v_errflag    
    then do:
    /* message "SP PR" vc_traceid view-as alert-box. */
    {us/bbi/gprun.i ""xxsuppliercrapi.p"" "(input vc_traceid,
                                             input  vc_import,
                                             output v_errflag,
                                             output v_apiresult)"}
     end.
    if v_errflag then 
    do:
    v_errorcnt = v_errorcnt + 1.
    v_errorstatus = yes.
    create api_status.
                  assign api_status.data_seq     = v_errorcnt
                         api_status.return_status  = "FAILED"
                         api_status.message_type = "AFTER-Validtion"
                         api_status.message_string  = v_apiresult
                         api_status.dataid  =  ""
                         api_status.billnbr = tt_tcreditor.CreditorCode                   
                         api_status.traceid = vc_traceid 
                         api_status.domain = global_domain.
    
    end.
    
    if not v_errflag and vc_import
    then do:
        
    /**** cim load 2.3.1 ****/
     cimloop:
     do transaction on error undo cimloop, retry cimloop:
                     assign
                         m_cimfile     =  tt_tcreditor.CreditorCode + string(day(today)) + string(month(today)) 
                                         + string(year(today))  + string(time) + ".cim".
                         m_logfile     =  tt_tcreditor.CreditorCode + string(day(today)) + string(month(today)) + 
                                                                 string(year(today))  + string(time) + ".log".
                     output to value (m_workpath + m_cimfile).
                     put unformatted 
                        tt_tcreditor.CreditorCode   skip                          /* supplier address */
                        "-" " " "-" " " "-" " " "-" " "  tt_tcreditor.tt_site " " "-" " " "-" " " "-" skip  /* supplier data */
                        "-" " " "-" " " "-" " " "-" " " "NO" skip              /* supplier pricing data  */
                        "-" skip                                             /* enterprise material transfer data */
                        "-" skip                                             /* supplier terms data */
                        "-" skip                                             /* tax */
                        "." skip
                        "." skip.
                      
                                          output close.

                      batchrun = yes.
                      output to  value( m_workpath + m_logfile).
                      input from value(m_workpath + m_cimfile).
                         {us/bbi/gprun.i ""advnmt.p""}
                      input close.
                      output close.
                      batchrun = no.

                     assign 
                        v_errflag     = no
                        v_apiresult = ""
                        m_line    = "".

                     input from value(m_workpath + m_logfile).
                     repeat:
                            import unformatted m_line.
                        if ( index(m_line, "error") <> 0 or 
                              index(m_line, "**") <> 0 )  and index (m_line, "tax zone: error") = 0 
                              and index (m_line , "**sac" ) = 0
                     
                        then do:
                             assign 
                               v_errflag     = yes
                               v_apiresult = m_line.
                               leave.
                        end.  /* end if */
                     end. /* end repeat */
                     input close.

                     if v_errflag then
                     do:
 
                         /*cim file*/
                         if search(m_workpath + m_cimfile) <> ? then 
                         do:
                                                   unix silent value("chmod 766 " + (m_workpath + m_cimfile)).
                           unix silent value( "mv -f " + (m_workpath + m_cimfile) + ' ' +  m_outpath + " 2>/dev/null" ).
                           
                         end.              
                         if search(m_workpath + m_logfile) <> ? then
                                                 do:
                                                   unix silent value("chmod 766 " + (m_workpath + m_logfile)).
                           unix silent value("mv -f " + (m_workpath + m_logfile) + ' ' +  m_outpath + " 2>/dev/null").
                                                 end.
                         undo cimloop, leave cimloop.
                     end. /* if m_err = yes then */
                     else
                     do:
                        
                         if search(m_workpath + m_logfile) <> ? then
                                                 do:
                                                 unix silent value("chmod 766 " + (m_workpath + m_logfile)).
                         unix silent value("rm -f " + m_workpath + m_logfile  + " 2>/dev/null").
                         end.
                         if search( m_workpath + m_cimfile) <> ? then
                                                 do:
                                                 unix silent value("chmod 766 " + (m_workpath + m_cimfile)).
                         unix silent value("rm -f " + m_workpath + m_cimfile  + " 2>/dev/null" ).
                                                 end.

                       
                     end. /*else do*/
                     
                         if v_errflag then 
                         do:
                         v_errorcnt = v_errorcnt + 1.
                         v_errorstatus = yes.
                         create api_status.
                                       assign api_status.data_seq     = v_errorcnt
                                              api_status.return_status  = "FAILED"
                                              api_status.message_type = "AFTER-Validtion"
                                              api_status.message_string  = v_apiresult
                                              api_status.dataid  =  ""
                                              api_status.billnbr = tt_tcreditor.CreditorCode                   
                                              api_status.traceid = vc_traceid 
                                              api_status.domain = global_domain.
                         
                         end.
                     else 
                     do:
                     v_errorcnt = v_errorcnt + 1.
                  create api_status.
                  assign api_status.data_seq     = v_errorcnt
                         api_status.return_status  = "SUCCESS"
                         api_status.message_type = "AFTER-Validtion"
                         api_status.message_string  = ""
                         api_status.dataid  =  ""
                         api_status.billnbr = tt_tcreditor.CreditorCode                   
                         api_status.traceid = vc_traceid 
                         api_status.domain = global_domain.
                     end.
                     
                  end. /*cim loop*/  
        
        end. /* if not v_errflag */
        
         /* Create output json */                   
         run writejsonfile(input hresult,
                  input vc_outputjson,
                  input "FILE",
                  input True,
                  input "UTF-8",
                  output vl_RetOK,
                  output vc_errorstring).
        

 end. /* for each tt_tcreditor */
 
 
  
       /* Create api log data record */
       for each tt_tcreditor.
       
       
      
        vi_reccount = vi_reccount + 1.   
        
        run CreateAPILogMaster(input vc_traceid,
                              input "xxsuppliermainapi",
                              input "xxsuppliermainapi.p",
                              input vc_topath + v_cim,
                              input vc_topath + v_log,
                              input vc_topath + vc_inputjson,
                              input tt_tcreditor.creditorcode,
                              input "",
                              input "",
                              input vi_reccount).

       end. /* if last-of(ttwomstr.wo_loc) then do: */
     
  
       
         do vi_filecount = 1 to 5:
          /* when success move cim log file to archive directory  */
          /* when failed move cim log file to error directory  */   
          /*  move status json file to out directory for API return */   
          /* when success move previous step .p and json file to archive directory  */
          /* when failed move previous step .p and json file to error directory  */       
          case vi_filecount:
      
          when 1 then
          assign vc_filename = replace(vc_inputjson,".json",".p")
                 vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
          when 2 then
          assign vc_filename = vc_inputjson
                 vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
          when 3 then
          assign vc_filename = replace(vc_inputjson,".json",".dat")
                 vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
          when 4 then
          assign vc_filename = replace(vc_inputjson,".json",".run.log")
                 vc_topath   = m_outpath.
          when 5 then
          assign vc_filename = replace(vc_inputjson,".json",".run.out.json")
                 vc_topath   =  m_outpath.
          end case.
          
        
        
        
        
          
          run cimfilehandle(input vc_filename,
                            input vc_topath,
                            input no ).                 
                   
          
     
       end.       /* do vi_filecount = 1 to 5: */        
    

      leave mainloop.    
 end. /* mainloop repeat */
 

 